<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    top="5vh"
    width="40%"
  >
    <el-form
      ref="createOrEditUserForm"
      :model="form"
      :rules="formRules"
    >
      <el-tabs v-model="tabValue" v-loading="loading">
        <el-tab-pane :label="$t('AbpIdentity[\'UserInformations\']')" name="first">
          <el-row :gutter="50">
            <el-col :span="12">
              <el-form-item :label="$t('BookStore2[\'DisplayName:UserName\']')" prop="userName">
                <el-input v-model="form.userName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('AbpIdentity[\'DisplayName:Name\']')" prop="name">
                    <el-input v-model="form.name" :placeholder="$t('AbpIdentity[\'DisplayName:Name\']')" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('AbpIdentity[\'DisplayName:Surname\']')" prop="surname">
                    <el-input v-model="form.surname" :placeholder="$t('AbpIdentity[\'DisplayName:Surname\']')" />
                  </el-form-item>
                </el-col>
              </el-row>

            </el-col>
          </el-row>
          <el-row :gutter="50">
            <el-col :span="12">
              <el-form-item :label="$t('AbpIdentity[\'DisplayName:Email\']')" prop="email">
                <el-input v-model="form.email" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('AbpIdentity[\'DisplayName:PhoneNumber\']')" prop="phoneNumber">
                <el-input v-model="form.phoneNumber" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="50">
            <el-col :span="12">
              <el-form-item :label="$t('BookStore2[\'DisplayName:Address\']')" prop="extraProperties.Address">
                <el-input v-model="form.extraProperties.Address" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('BookStore2[\'DisplayName:EntryDate\']')" prop="extraProperties.EntryDate">
                    <el-date-picker v-model="form.extraProperties.EntryDate" type="date" value-format="yyyy-MM-dd" style="width: 100%;" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('BookStore2[\'DisplayName:LeaveDate\']')" prop="extraProperties.LeaveDate">
                    <el-date-picker v-model="form.extraProperties.LeaveDate" type="date" value-format="yyyy-MM-dd" style="width: 100%;" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row :gutter="50">
            <el-col :span="12">
              <el-form-item :label="$t('BookStore2[\'DisplayName:SocialSecurityCard\']')" prop="extraProperties.SocialSecurityCard">
                <el-input v-model="form.extraProperties.SocialSecurityCard" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('BookStore2[\'DisplayName:Credits\']')" prop="extraProperties.Credits">
                    <el-input v-model="form.extraProperties.Credits" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('BookStore2[\'Parcels\']')" prop="extraProperties.Parcels">
                    <el-input v-model="form.extraProperties.Parcels" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-form-item v-if="actionMode !== 'edit'" :label="$t('AbpIdentity[\'DisplayName:Password\']')" prop="password">
            <el-input v-model="form.password" type="password" />
          </el-form-item>
          <el-form-item prop="lockoutEnabled">
            <el-checkbox
              v-model="form.lockoutEnabled"
              :label="$t('AbpIdentity[\'DisplayName:LockoutEnabled\']')"
              name="type"
            />
          </el-form-item>
          <el-row :gutter="50">
            <el-col :span="12">
              <el-form-item :label="$t('BookStore2[\'DisplayName:PortraitImg\']')" prop="extraProperties.PortraitBlob">
                <single-file-upload ref="portraitUpload" :attach-file="form.extraProperties.PortraitBlob" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('BookStore2[\'DisplayName:SocialSecurityCardImg\']')" prop="extraProperties.SocialSecurityCardBlob">
                <single-file-upload ref="socialSecurityCardUpload" :attach-file="form.extraProperties.SocialSecurityCardBlob" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane :label="$t('AbpIdentity[\'Roles\']')" name="second">
          <el-form-item prop="roleNames">
            <el-checkbox-group v-model="form.roleNames">
              <el-checkbox
                v-for="role in assignableRoles"
                :key="role.name"
                :label="role.name"
              >{{ role.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane :label="$t('AbpIdentity[\'OrganizationUnits\']')" name="third">
          <el-form-item prop="organizationUnitIds">
            <el-tree
              ref="organizationUnitTree"
              :node-key="treeContext.nodeKey"
              :props="treeContext.props"
              :data="assignableOrganizationUnitsTree"
              default-expand-all
              check-on-click-node
              :expand-on-click-node="false"
              check-strictly
              show-checkbox
            />
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <!-- 隐藏表单 -->
      <el-form-item prop="id" hidden>
        <el-input v-model="form.id" />
      </el-form-item>
      <el-form-item prop="concurrencyStamp" hidden>
        <el-input v-model="form.concurrencyStamp" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">{{ $t('AbpIdentity[\'Cancel\']') }}</el-button>
      <el-button type="primary" @click="submitForm">
        <i class="el-icon-check" />
        {{ $t('AbpIdentity[\'Save\']') }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  getById,
  create,
  edit,
  getUserRoles,
  getOrganizationUnits
} from '@/api/administration/user/user'
import SingleFileUpload from '@/views/components/single-file-upload'
export default {
  name: 'CreateOrEditUser',
  components: { SingleFileUpload },
  props: {
    context: {
      type: Object,
      required: true
    },
    visible: {
      type: Boolean,
      required: true,
      default: false
    },
    assignableRoles: {
      type: Array,
      required: true
    },
    assignableOrganizationUnitsTree: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      title: '',
      actionMode: '',
      loading: false,
      tabValue: 'first',
      treeContext: {
        props: {
          label: 'displayName',
          children: 'children'
        },
        nodeKey: 'id'
      },
      form: {
        id: '',
        concurrencyStamp: '',
        password: '',
        userName: '',
        name: '',
        surname: '',
        email: '',
        phoneNumber: '',
        lockoutEnabled: true,
        roleNames: [],
        organizationUnitIds: [],
        extraProperties: {
          EntryDate: null,
          LeaveDate: null,
          Address: '',
          Credits: '',
          PortraitBlob: {},
          PortraitBlob_BlobName: '',
          PortraitBlob_FileName: '',
          PortraitBlob_BlobContainerName: '',
          SocialSecurityCard: '',
          SocialSecurityCardBlob: {},
          SocialSecurityCardBlob_BlobName: '',
          SocialSecurityCardBlob_FileName: '',
          SocialSecurityCardBlob_BlobContainerName: '',
          Parcels: ''
        }
      },
      formRules: {
        userName: [{ required: true, message: this.$t('AbpIdentity[\'Required\']'), trigger: 'blur' }],
        password: [{ required: true, message: this.$t('AbpIdentity[\'Required\']'), trigger: 'blur' }],
        email: [
          { required: true, message: this.$t('AbpIdentity[\'Required\']'), trigger: 'blur' },
          { type: 'email', message: this.$t('AbpIdentity[\'ThisFieldIsNotAValidEmailAddress.\']'), trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  watch: {
    context(newVal, oldVal) {
      this.loading = true
      this.$nextTick(function() {
        this.title = newVal.title
        this.actionMode = newVal.actionMode

        if (this.actionMode === 'edit') {
          /* 编辑模式 */

          if (newVal.id) {
            Promise.all([
              getById(newVal.id),
              getUserRoles(newVal.id),
              getOrganizationUnits(newVal.id)
            ]).then((value) => {
              const user = value[0]
              const userRoles = value[1].items
              const organizationUnits = value[2].items

              // 人员
              if (user) {
                this.form.id = newVal.id
                this.form.concurrencyStamp = user.concurrencyStamp
                this.form.userName = user.userName
                this.form.surname = user.surname
                this.form.name = user.name
                this.form.email = user.email
                this.form.phoneNumber = user.phoneNumber
                this.form.lockoutEnabled = user.lockoutEnabled
                this.form.extraProperties.Parcels = user.extraProperties.Parcels
                this.form.extraProperties.EntryDate = user.extraProperties.EntryDate
                this.form.extraProperties.LeaveDate = user.extraProperties.LeaveDate
                this.form.extraProperties.Address = user.extraProperties.Address
                this.form.extraProperties.Credits = user.extraProperties.Credits
                this.form.extraProperties.SocialSecurityCard = user.extraProperties.SocialSecurityCard
                if (user.extraProperties.PortraitBlob_BlobName) {
                  this.form.extraProperties.PortraitBlob = {
                    blobName: user.extraProperties.PortraitBlob_BlobName || '',
                    fileName: user.extraProperties.PortraitBlob_FileName || '',
                    blobContainerName: user.extraProperties.PortraitBlob_BlobContainerName || ''
                  }
                }
                if (user.extraProperties.SocialSecurityCardBlob_BlobName) {
                  this.form.extraProperties.SocialSecurityCardBlob = {
                    blobName: user.extraProperties.SocialSecurityCardBlob_BlobName || '',
                    fileName: user.extraProperties.SocialSecurityCardBlob_FileName || '',
                    blobContainerName: user.extraProperties.SocialSecurityCardBlob_BlobContainerName || ''
                  }
                }
              }
              // 拥有的角色
              if (userRoles) {
                userRoles.forEach(val => {
                  this.form.roleNames.push(val.name)
                })
              }
              // 拥有的组织
              if (organizationUnits) {
                organizationUnits.forEach(val => this.form.organizationUnitIds.push(val.id))
                this.$refs.organizationUnitTree.setCheckedKeys(this.form.organizationUnitIds)
              }
              this.loading = false
            })
          }
        } else {
          /* 创建模式 */

          // 默认角色
          if (this.assignableRoles) {
            this.assignableRoles.forEach(val => {
              if (val.isDefault) {
                this.form.roleNames.push(val.name)
              }
            })
          }
          this.loading = false
        }
      })
    }
  },
  methods: {
    async submitForm() {
      this.$refs.createOrEditUserForm.validate(async(isValid, invalidFields) => {
        if (isValid) {
          this.form.extraProperties.SocialSecurityCardBlob_BlobContainerName = this.form.extraProperties.SocialSecurityCardBlob.blobContainerName
          this.form.extraProperties.SocialSecurityCardBlob_BlobName = this.form.extraProperties.SocialSecurityCardBlob.blobName
          this.form.extraProperties.SocialSecurityCardBlob_FileName = this.form.extraProperties.SocialSecurityCardBlob.fileName
          this.form.extraProperties.PortraitBlob_BlobContainerName = this.form.extraProperties.PortraitBlob.blobContainerName
          this.form.extraProperties.PortraitBlob_BlobName = this.form.extraProperties.PortraitBlob.blobName
          this.form.extraProperties.PortraitBlob_FileName = this.form.extraProperties.PortraitBlob.fileName
          if (!this.form.extraProperties.EntryDate) {
            this.form.extraProperties.EntryDate = null
          }
          if (!this.form.extraProperties.LeaveDate) {
            this.form.extraProperties.LeaveDate = null
          }
          this.form.organizationUnitIds = this.$refs.organizationUnitTree.getCheckedKeys()
          if (this.actionMode === 'edit') {
            await edit(this.form.id, this.form)
          } else {
            await create(this.form)
          }
          this.$message({ message: this.$t('AbpIdentity[\'Ok\']'), type: 'success' })
          this.closeDialog()
          this.$emit('saveSucceed')
        }
      })
    },
    closeDialog() {
      this.resetDialog() // 重置表单
      this.$emit('update:visible', false)
    },
    resetDialog() {
      this.$refs.createOrEditUserForm.resetFields()
      this.$refs.organizationUnitTree.setCheckedKeys([])
      this.tabValue = 'first'

      this.form.extraProperties.SocialSecurityCardBlob_BlobContainerName = ''
      this.form.extraProperties.SocialSecurityCardBlob_BlobName = ''
      this.form.extraProperties.SocialSecurityCardBlob_FileName = ''

      this.form.extraProperties.PortraitBlob_BlobContainerName = ''
      this.form.extraProperties.PortraitBlob_BlobName = ''
      this.form.extraProperties.PortraitBlob_FileName = ''
    }
  }
}
</script>

<style scoped>
</style>
